package com.company;


import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

public class BankClient {
    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;

    BankClient() {
    }

    void run() {
        try {
            requestSocket = new Socket("localhost", 2013);
            System.out.printf("Connected to localhost in port 2013\n");
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            in = new ObjectInputStream(requestSocket.getInputStream());
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            try {
                message = (String) in.readObject();
                System.out.printf("server>%s\n", message);
                do {
                    message = input.readLine();
                    sendMessage(message);
                    StringTokenizer stoken = new StringTokenizer(message, " ");
                    if(stoken.hasMoreTokens()){
                        if(stoken.nextToken().equals("get")) {
                                 System.out.printf("server>%s\n", (String)in.readObject());
                        }
                    }
                } while (!message.equals("bye"));
            } catch (ClassNotFoundException classNot) {
                System.err.printf("data received in unknown format\n");
            }
        } catch (UnknownHostException unknownHost) {
            System.err.printf("You are trying to connect to an unknown host!\n");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        catch (Exception e) {
            System.err.printf("Write to protect memory!\n");
        } finally {
            try {
                in.close();
                out.close();
                requestSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    void sendMessage(final String msg) {
        try {
            out.writeObject(msg);
            out.flush();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public static void main(final String args[]) {
        BankClient client = new BankClient();
        client.run();
    }

}
